package com.xsb.mvvmlibrary.base

import android.net.ParseException
import android.util.Log
import com.google.gson.JsonParseException
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import org.json.JSONException
import retrofit2.HttpException
import java.io.InterruptedIOException
import java.net.ConnectException
import java.net.UnknownHostException

/**
 *     author : 薛少博
 *     e-mail : xsb@zlhopesun.com
 *     time   : 2021/5/20
 *     desc   : 类说明
 */
abstract class BaseObserver<T> : Observer<T> {
    protected var errorMessage = "服务器异常"
    override fun onNext(response: T) {
        onSuccess(response)
    }

    override fun onError(e: Throwable) {
        Log.e("错误", e.toString())
        var errMsg = "未知错误"
        if (e is HttpException) {
            //   HTTP错误
            errMsg = "HTTP错误"
            onException(BAD_NETWORK, errMsg)
        } else if (e is ConnectException
            || e is UnknownHostException
        ) {
            //   连接错误
            errMsg = "连接错误"
            onException(CONNECT_ERROR, errMsg)
        } else if (e is InterruptedIOException) {
            //  连接超时
            errMsg = "连接超时"
            onException(CONNECT_TIMEOUT, errMsg)
        } else if (e is JsonParseException
            || e is JSONException
            || e is ParseException
        ) {
            //  解析错误
            errMsg = "解析错误"
            onException(PARSE_ERROR, errMsg)
            e.printStackTrace()
        } else {
            if (e != null) {
                errMsg = e.toString()
                onError(errMsg, 9999)
            } else {
                errMsg = "未知错误"
                onError(errMsg, 9999)
            }
        }
    }

    private fun onException(unknownError: Int, message: String) {
        when (unknownError) {
            CONNECT_ERROR -> onError("连接错误", CONNECT_ERROR)
            CONNECT_TIMEOUT -> onError("连接超时", CONNECT_TIMEOUT)
            BAD_NETWORK -> onError("网络超时", BAD_NETWORK)
            PARSE_ERROR -> onError("数据解析失败", PARSE_ERROR)
            NOT_TRUE_OVER -> onError(message, 9999)
            else -> {
            }
        }
    }

    /**
     * 回调正常数据
     */
    protected abstract fun onSuccess(data: T)

    /**
     * 回调失败
     */
    protected abstract fun onError(msg: String?, code: Int)

    companion object {
        /**
         * 网络连接失败  无网
         */
        const val NETWORK_ERROR = 100000

        /**
         * 解析数据失败
         */
        const val PARSE_ERROR = 1008

        /**
         * 网络问题
         */
        const val BAD_NETWORK = 1007

        /**
         * 连接错误
         */
        const val CONNECT_ERROR = 1006

        /**
         * 连接超时
         */
        const val CONNECT_TIMEOUT = 1005

        /**
         * 其他所有情况
         */
        const val NOT_TRUE_OVER = 1004

        //成功
        const val SUCCESS = 200
    }

    override fun onComplete() {

    }

    override fun onSubscribe(d: Disposable) {

    }
}
